'''
Created on 2010-8-17

@author: madlee
'''

import wx
from os import path
from time import time as now

class Document:
    def __init__(self, doctype, filename=None):
        self.type = doctype
        if filename:
            self.filename = path.abspath(filename)
        else:
            self.filename = None
        self.views = []
        self.load_time = self.modify_time = now()
        if self.filename is not None:
            self.load()

    def get_icon(self):
        return self.doctype.get_icon()

    def get_title(self):
        _, name = path.split(self.filename)
        return name

    def update(self, source, *args, **kwargs):
        for i in self.views:
            if i != source:
                i.on_update(*args, **kwargs)
        self.modify_time = now()
        
    @property
    def is_dirty(self):
        return self.modify_time > self.load_time

    def load(self):
        self.load_time = self.modify_time = now()
    
    def save(self):
        if self.filename is None:
            # TODO:
            pass
        self.save_as(self, self.filename)

    def save_as(self, target):
        """Write this document into target file. Please update this method for
different data. and remember call the parent method at the end of your 
method to ensure clear up"""
        self.load_time = self.modify_time = now()
        
    @property
    def saving_filters(self):
        return self.doctype.saving_filters
    

class View:
    def __init__(self, doc):
        self.document = doc
        doc.views.append(self)
    
    def on_close(self):
        self.document.views.remove(self)
        
    def on_update(self, *args, **kwargs):
        pass

class DocumentType:
    @property
    def openning_filters(self):
        raise NotImplementedError()
    
    def get_files(self, filename):
        return [filename]
 
    def create_document(self, filename):
        raise NotImplementedError()
    
    def create_view(self, document):
        raise NotImplementedError()
    
    
class TextView(View, wx.TextCtrl):
    def __init__(self, doc, *args, **kwargs):
        View.__init__(self, doc)
        wx.TextCtrl.__init__(self, *args, **kwargs)
        self.on_update()

    def on_close(self):
        View.on_close(self)
        
    def on_update(self, *args, **kwargs):
        self.SetValue(self.document.get_text())
        
class TextDocument(Document):
    def __init__(self, doctype, filename=None):
        Document.__init__(self, doctype, filename)
